import Cookies from 'js-cookie';

const user = {
    state: {},
    mutations: {
        logout() {
            Cookies.remove('userInfo');
            // 清空打开的页面等数据
            localStorage.clear();
        }
    }
};

const sessionutil = {
    setSession(key, value, maxAge) { //key=userInfo  value=2  maxAge=''  ||  可自行设置
        const maxAgeTime = new Date().getTime() + 1000 * 3600; // 当前时间的+1小时 session 过期时间
        try {
            let data = { value, maxAge: maxAge ? maxAge : maxAgeTime }
            sessionStorage.setItem(typeof key === 'string' ? key : JSON.stringify(key), JSON.stringify(data))
        } catch (err) {
        }
    },
    getSession(key) {
        try {
            const maxAgeTime = new Date().getTime() + 1000 * 3600; // 首先先设置一个 session 过期时间 1H后可自行设置
            let date = new Date().getTime();  //当前时间
            let session = JSON.parse(sessionStorage.getItem(typeof key === 'string' ? key : JSON.stringify(key)));
            if (session && session.maxAge != null && session.maxAge - date > 0 && session.maxAge <= maxAgeTime) {
                this.setSession(key, session.value);
                return session.value;
            } else {
                return null;
            }
        } catch (err) {
        }
    },
}


export default user;
